//
//  DailyCollectionViewController.m
//  OpenYourEyes
//
//  Created by apple on 15/8/12.
//  Copyright (c) 2015年 zhanglei. All rights reserved.
//

#import "DailyCollectionViewController.h"
#import "DailyCollectionViewCell.h"
#import "DailyFooterReusableView.h"
#import "Header.h"
#import "TotalScrollViewController.h"

/**
 *  判断下拉刷新和上拉加载
 */
typedef NS_ENUM(NSInteger, RefreshType){
    /**
     *  下拉刷新
     */
    RefreshTypeNew,
    /**
     *  上拉加载
     */
    RefreshTypeMore
};
@interface DailyCollectionViewController ()<MBProgressHUDDelegate>
{
    MBProgressHUD *_HUD;  //  数据加载菊花
}
/** 判断加载刷新*/
@property (nonatomic, assign) RefreshType refreshType;
/** 存储数据数组*/
@property (nonatomic ,strong) NSMutableArray *dataSource;
/** 下一天的路径*/
@property (nonatomic, strong) NSString *nextUrl;
/** 存储解析出来的数据的data*/
@property (nonatomic ,strong) NSData *getData;
/** 下一个解析的Data*/
@property (nonatomic ,strong) NSData *nextData;

@end

@implementation DailyCollectionViewController

/**
 *  懒加载
 *
 *  @return dataSource
 */
- (NSMutableArray *)dataSource
{
    if (_dataSource == nil)
    {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

/**
 *  数据加载菊花控件初始化
 */
- (void)addMBProgressHUD
{
    if(_dataSource.count == 0)
    {
        //初始化菊花加载
        _HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //设置代理
        _HUD.delegate = self;
        //如果设置此属性则当前的view置于后台
        _HUD.dimBackground = YES;
        //设置对话框文字
        _HUD.labelText = @"请稍等";
    }
}

/**
 *  注册类
 */
- (void)addRegisterClass
{
    //注册cell
    [self.collectionView registerClass:[DailyCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //注册CollectionView中footer
    [self.collectionView registerClass:[DailyFooterReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
}

/**
 *  下拉刷新
 */
- (void)addRefreshTypeNew
{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        //调用解析数据方法
        [weakSelf requestData];
        _refreshType = RefreshTypeNew;
        
    }];
}

/**
 *  加载更多
 */
- (void)addRefreshTypeMore
{
    __weak __typeof(self) weakSelf = self;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _refreshType = RefreshTypeMore;
        [weakSelf requestNextData];
        
    }];
}



/**
 *  结束刷新数据
 */
- (void)addEndRefreshing
{
    // 拿到当前的上拉刷新控件，结束刷新状态
    [self.collectionView.footer endRefreshing];
    // 拿到当前的下拉刷新控件，结束刷新状态
    [self.collectionView.header endRefreshing];
    //刷新数据
    [self.collectionView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [self requestData];
    
    //注册类
    [self addRegisterClass];
    //数据加载菊花控件初始化
    [self addMBProgressHUD];
    //下拉刷新
    [self addRefreshTypeNew];
    //加载更多
    [self addRefreshTypeMore];
}

/**
 *  请求数据
 */
- (void)requestData
{
    NSDictionary *num = @{@"num":@"5"};
    
    [PKRequestManager manager:POST requestWith:@"http://baobab.wandoujia.com/api/v1/feed" parDic:num finish:^(NSData *data)
     {
         self.getData = data;
         //解析数据

         [self addRequestData];
         
     } error:^(NSError *error)
     {
         
     }];
}

/**
 *  解析数据
 */
- (void)addRequestData
{

    NSData *data = nil;
    
    //判断是下来加载还是加载更多
    if (_refreshType == RefreshTypeMore)
    {
        data = self.nextData;
    }
    else
    {
        data = self.getData;
    }
    
    //数据加载出来隐藏菊花
    [_HUD hide:YES];
    //解析数据
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    //获取字典dailyList的数据
    NSArray *dailyList = dict[@"dailyList"];
    if (_refreshType == RefreshTypeNew)
    {
        [_dataSource removeAllObjects];
    }
    self.nextUrl = dict[@"nextPageUrl"];
    
    for (NSDictionary *dic in dailyList)
    {
        NSArray *arr = dic[@"videoList"];
        NSMutableArray *marr = [NSMutableArray array];
        for (NSDictionary *dataDic in arr)
        {
            //利用KVC来存储数据
            DailyModel *model = [[DailyModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [marr addObject:model];
        }
        [self.dataSource addObject:marr];
        
    }
    //结束刷新数据
    [self addEndRefreshing];
}

/**
 *  上拉加载
 */
- (void)requestNextData
{
    [PKRequestManager manager:POST requestWith:self.nextUrl parDic:nil finish:^(NSData *data) {
        
        self.nextData = data;
        [self addRequestData];
    } error:^(NSError *error) {
        
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _dataSource.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *arr = _dataSource[section];
    
    return arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //cell的重用
    DailyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    //获取cell的数据
    NSMutableArray *marr = _dataSource[indexPath.section];
    DailyModel *model = marr[indexPath.item];
    cell.model = model;
    
    //改变图片移动的位置
    CGFloat yOffset = ((self.collectionView.contentOffset.y - cell.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED;
    cell.imageOffset = CGPointMake(0.0f, yOffset);
    
    return cell;
}
//点击每个cell触发的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{    
    if (_pushBlock != nil)
    {
        _pushBlock(_dataSource,indexPath.row,indexPath.section);
    }    
}

#pragma mark <UICollectionViewDelegate>

//设置CollectionView的Footer
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //获取数据
    NSMutableArray *marr = _dataSource[indexPath.section];
    DailyModel *model = marr[indexPath.row];
    //显示footer上面的数据,由于获取的数据是乘了1000倍，所有要除以1000，而86400刚好是一天时间的秒数，意思就是减去一天的时间
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:model.date/1000 - 86400];
    //格式化时间
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    //设置格式
    [formater setDateFormat:@"-MMM.dd-"];
    formater.timeZone = [NSTimeZone systemTimeZone];
    formater.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-us"];
    NSString *string = [formater stringFromDate:date];
    //截取要显示的时间

    
    //重用
    DailyFooterReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
    //把获取并截取好的时间传值
    view.dateTime = string;
    return view;
}

//设置cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(kWidth, 200);
}

#pragma mark - UIScrollViewdelegate methods
//设置移动过程改变的样式方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    for(DailyCollectionViewCell *view in self.collectionView.visibleCells)
    {
        CGFloat yOffset = ((self.collectionView.contentOffset.y - view.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED;
        view.imageOffset = CGPointMake(0.0f, yOffset);
    }
}

@end
